package cn.jinjimi.app.poster.fragment;

import android.os.Handler;
import android.support.v4.view.ViewPager;

import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.framework.helper.annotation.EventTraceWhenTrue;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.domain.data.dto.NoticePosterJinjuDTO;
import cn.jinjimi.app.managers.NoticeManager;
import cn.jinjimi.app.managers.PosterCacheManager;
import cn.jinjimi.app.poster.activity.PosterListActivity;
import cn.jinjimi.app.poster.bean.PosterTemplate;
import cn.jinjimi.app.poster.interfaces.PosterActivityView;
import cn.jinjimi.app.poster.presenter.PosterHomePresenter;
import cn.jinjimi.app.main.adapter.FragmentPageAdapter;
import cn.jinjimi.app.main.extend.BaseNetControlFragment;
import cn.jinjimi.app.main.widget.PagerSlidingTabStrip;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Created by lforxeverc on 16/9/27.
 */

public class PosterContainerFragment extends BaseNetControlFragment implements ViewPager.OnPageChangeListener, PosterActivityView {
    private ViewPager vpPoster;
    private PagerSlidingTabStrip indicator;
    private PosterHomePresenter mPresenter;
    private int jumpPosition = 0;
    private int jumpCid;
    private List<PosterTemplate> categories;
    private List<NoticePosterJinjuDTO> noticePosterDTOs;
    private int dataType = DataType.INFORMATION_POSTER;

    public interface LoadType {
        int LOAD_WAIT = 0;
        int LOAD_CACHE = 1;
        int LOAD_NET = 2;
        int LOAD_CACHE_NET = 3;
    }

    //数值不允许修改
    public interface DataType {
        int PRODUCT_POSTER = 1;
        int INFORMATION_POSTER = 2;
        int JINJU_POSTER = 3;
    }

    @Override
    protected int getBizLayoutResourceId() {
        return R.layout.fragment_poster_home;
    }

    @Override
    protected void initialBiz() {
        String cid = getActivity().getIntent().getStringExtra(BundleKey.POSTER_CID);
        String type = getActivity().getIntent().getStringExtra(BundleKey.TYPE);
        //路由传的type 0=海报 1=金句
        if (!StringUtils.isEmpty(type) && type.equals(PosterListActivity.ROUTER_TYPE_JINJU)) {
            dataType = DataType.JINJU_POSTER;
        } else {
            dataType = DataType.INFORMATION_POSTER;
        }
        if (!StringUtils.isEmpty(cid)) {
            jumpCid = Integer.parseInt(cid);
        }
        vpPoster = (ViewPager) findView().findViewById(R.id.vp_posters);
        indicator = (PagerSlidingTabStrip) findView().findViewById(R.id.indicator_tabs);
        indicator.setOnPageChangeListener(this);
        mPresenter = new PosterHomePresenter(this);
        mPresenter.setLoadType(dataType);
        categories = PosterCacheManager.getInstance().getCategory(dataType);
        initView(categories, LoadType.LOAD_CACHE);
        initRed(noticePosterDTOs);
    }

    @Override
    protected void loadData() {
        mPresenter.loadCategory(dataType);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        setRedPointAnalyse(position, String.valueOf(categories.get(position).code), dataType == DataType.INFORMATION_POSTER);

    }

    @EventTrace(EventID.APP_POSTER_TAB_CHANGE)
    private void setRedPointAnalyse(@EventTraceParam(value = EventDataField.ParamPostion, isValueAutoPlusOne = true) int position,
                                    @EventTraceParam(EventDataField.ParamId) String code, @EventTraceWhenTrue boolean analyse) {
        indicator.setRedStatus(position, false);
        RedInformModel.setHasShown(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void showError() {
        categories = PosterCacheManager.getInstance().getCategory(dataType);
        if (categories != null && !categories.isEmpty()) {
            netLoadSucc();
            initView(categories, LoadType.LOAD_CACHE_NET);
            initRed(noticePosterDTOs);
        } else {
            netLoadFaiEmpty();
        }

    }

    @Override
    public void loadSuccess(List<PosterTemplate> data) {
        netLoadSucc();
        PosterCacheManager.getInstance().saveCategory(dataType, data);
        categories = data;
        initView(data, LoadType.LOAD_CACHE_NET);
        initRed(noticePosterDTOs);
    }

    @Override
    public void setRedInfo(List<NoticePosterJinjuDTO> noticePosterDTOs) {
        this.noticePosterDTOs = noticePosterDTOs;
        initRed(noticePosterDTOs);
    }

    public void initView(List<PosterTemplate> templateList, int loadtype) {
        if (templateList == null || templateList.size() <= 0) return;
        List<PosterFragment> fmList = new ArrayList<>();

        for (PosterTemplate temp : templateList) {
            if (temp.code == jumpCid) {
                jumpPosition = templateList.indexOf(temp);
            }
            PosterFragment fm = PosterFragment.create(loadtype, temp.title, temp.parentCode, temp.code, null, null);
            fm.setPosition(templateList.indexOf(temp));
            fmList.add(fm);
        }
        FragmentPageAdapter adapter = new FragmentPageAdapter(getChildFragmentManager(), fmList);
        vpPoster.setAdapter(adapter);
        indicator.setViewPager(vpPoster);

    }

    private void initRed(List<NoticePosterJinjuDTO> noticePosterDTO) {
        if (categories == null || indicator == null) return;
        indicator.resetAllRedPoints();
        RedInformModel.sort(noticePosterDTO);
        for (PosterTemplate temp : categories) {
            if (RedInformModel.hasRedInfoWithCode(temp.code)) {
                int position = categories.indexOf(temp);
                RedInformModel.addPosition(position, temp.code);
                if (position == 0)
                    RedInformModel.setHasShown(0);
            }
        }
        for (Integer p : RedInformModel.getRedPosition())
            indicator.setRedStatus(p, true);
    }

    boolean firstFlag = true;

    @Override
    public void onResume() {
        super.onResume();
        if (firstFlag) {
            firstFlag = false;
            if (jumpPosition == 0) return;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    vpPoster.setCurrentItem(jumpPosition);
                }
            }, 500);

        }
    }

    @Override
    public void onDestroy() {
        if (mPresenter != null)
            mPresenter.onDestroy();
        super.onDestroy();
    }

    static class RedInformModel {
        static List<NoticePosterJinjuDTO> mRawData;
        static Map<Integer, List<NoticePosterJinjuDTO>> mCateGroup;
        private static Map<Integer, Integer> mPositionsCates;

        private static void reset() {
            mCateGroup = new HashMap<>();
            mPositionsCates = new HashMap<>();

        }

        public static void sort(List<NoticePosterJinjuDTO> mData) {
            reset();
            mRawData = mData;
            if (mRawData != null && !mRawData.isEmpty()) {
                for (NoticePosterJinjuDTO data : mRawData) {
                    int categoryCode = data.categoryCode;
                    List<NoticePosterJinjuDTO> mContent = mCateGroup.get(categoryCode);
                    if (mContent == null) {
                        mContent = new ArrayList<>();
                    }
                    mContent.add(data);
                    mCateGroup.put(categoryCode, mContent);
                }
            }
        }

        public static Set<Integer> getRedPosition() {
            if (mPositionsCates != null)
                return mPositionsCates.keySet();
            return new HashSet<>();
        }

        public static boolean hasRedInfoWithCode(int code) {
            if (mCateGroup != null && mCateGroup.size() > 0) {
                List mList = mCateGroup.get(code);
                return (mList != null && !mList.isEmpty());
            }
            return false;
        }

        public static void addPosition(int position, int code) {
            mPositionsCates.put(position, code);
        }

        public static void setHasShown(int position) {
            if (mPositionsCates == null || !mPositionsCates.containsKey(position)) return;
            int cate = mPositionsCates.get(position);

            List<NoticePosterJinjuDTO> mList = mCateGroup.get(cate);
            if (mList == null || mList.isEmpty()) return;
            List<String> ids = new ArrayList<>();
            for (NoticePosterJinjuDTO data : mList) {
                ids.add(data.noticeId);
            }
            NoticeManager.clickNoticeByIds(ids.toArray(new String[ids.size()]));
            mPositionsCates.remove(position);
        }
    }

}
